package com.atguigu.lock;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: LDeng
 * @Date: 2021-09-05 12:34
 */

class ShareResource33{
    private int flag=1;

    Lock lock=new ReentrantLock();

    private Condition c1=lock.newCondition();
    private Condition c2=lock.newCondition();
    private Condition c3=lock.newCondition();

    public void print5(int loop) throws InterruptedException {
        lock.lock();
        try {
            //判断
            while(flag!=1){
                c1.await();
            }
            //干活
            for (int i = 1; i <=3; i++) {
                System.out.println(Thread.currentThread().getName()+"---"+i+"--轮数-"+loop);
            }
            //通知
            flag=2;//修改标志位2
            c2.signal();//通知BB线程
        }finally {
            lock.unlock();
        }
    }

    public void print10(int loop) throws InterruptedException {
        lock.lock();
        try {
            //判断
            while(flag!=2){
                c2.await();
            }
            //干活
            for (int i = 1; i <=3; i++) {
                System.out.println(Thread.currentThread().getName()+"---"+i+"--轮数-"+loop);
            }
            //通知
            flag=3;
            c3.signal();
        }finally {
            lock.unlock();
        }
    }

    public void print15(int loop) throws InterruptedException {
        lock.lock();
        try {
            while(flag!=3){
                c3.await();
            }
            for (int i = 1; i <=3 ; i++) {
                System.out.println(Thread.currentThread().getName()+"---"+i+"--轮数-"+loop);
            }
            flag=1;
            c1.signal();
        }finally {
            lock.unlock();
        }
    }
}

public class ThreadDemo33 {

    public static void main(String[] args) {
        ShareResource33 resource33=new ShareResource33();
        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    resource33.print5(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AAA").start();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    resource33.print10(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BBB").start();
        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    resource33.print15(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CCC").start();
    }

}
